const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const db = require('../model/index');
const moment = require('moment');
const User = db.models.User;
const ApprovalPrivileges = db.models.ApprovalPrivileges;
const RequestNote = db.models.RequestNote;
const UserRequestNote = db.models.UserRequestNote;
const Message = db.models.Message;
const { removeEmpty } = require('../lib/utilx');
const { noteTypes } = require('../../../client/src/conf/noteTypeConfig');
const sendMail = require('../lib/mail');

class RequestAndApprovalController {
  async getRequestNoteList(ctx) {
    const user = ctx.user;  // 得到用户
    let { page, limit, requestType, sStr, sType, sStatus, sTime } = ctx.request.body;
    if(sType === 'all')
      sType = null;
    if(sStatus === 'all')
      sStatus = null;

    let where = {};
    if(sStr) {
      where = Object.assign(where, {  // todo: 总是容易写到一个对象里面而不是写成数组
        [Op.or]: [{
          oid: {
            [Op.like]: `%${sStr}%`,
          }
        }, {
          title: {
            [Op.like]: `%${sStr}%`,
          }
        }]
      });
    }
    if(sType) {
      where = Object.assign(where, {
        type: sType,
      });
    }
    if(sTime) {
      where = Object.assign(where, {
        createdAt: {
          [Op.gte]: new Date(moment(sTime).startOf('day').unix() * 1000),
          [Op.lte]: new Date(moment(sTime).endOf('day').unix() * 1000),
        }
      });
    }


    if (requestType === 'user') {  // 如果是普通

      if(sStatus) {
        where = Object.assign(where, {
          userStatus: sStatus
        });
      }

      console.log(where);
      let totalCount = await RequestNote.count({
        where,
        include: [{
          model: User.scope('all'),
          attributes: ['username', 'id', 'phone', 'email'],
          through: {
            where: {
              UserId: user.id,
              step: 0,
            },
          },
        }],
      });
      let requestNoteList = await RequestNote.findAll({
        order: [
          ['id', 'DESC']
        ],
        attributes: [
          'id',
          'oid',
          'title',
          'type',
          'isRejected',
          'userStatus',
          'applicantName',
          'step',
          'createdTime',
        ],
        where,
        include: [{
          model: User.scope('all'),
          attributes: ['username', 'id', 'phone', 'email'],
          through: {
            where: {
              UserId: user.id,
              step: 0,
            },
          },
        }],
        limit: limit === -1 ? undefined : limit,
        offset: limit === -1 ? undefined : ( page - 1 ) * limit,
      });
      console.log(page, limit);
      // let userRequestNote = requestNoteList[0].Users[0].UserRequestNote;

      requestNoteList = requestNoteList.map((note) => {
        let typeName = '';
        noteTypes.forEach((config) => {
          if( config.enName === note.type ) {
            typeName = config.name;
          }
        });
        return Object.assign(note.dataValues, {
          applicant: note.applicantName,
          createdAt: note.createdTime,
          type: typeName,
          status: note.userStatus,
        });
      });

      ctx.body = {
        code: 0,
        msg: {
          total: totalCount,
          requestNoteList,
        }
      };

      return;



    } else if(requestType === 'approver') {  // 如果是审批员

      const approvalPrivileges = user.ApprovalPrivileges || [];  // 得到审批权限
      let totalCount = 0;
      let requestNoteList = [];

      for(let privilege of approvalPrivileges) {
        if( sStatus === '待审批' ) {  // 如果是待审批的内容
          where = Object.assign(where, {
            step: privilege.step,
            isRejected: false,   // 未被拒绝的
          });
        }
        if( sStatus === '我已同意' ) {  // 自己同意过的
          where = Object.assign(where, {
            step: {
              [Op.gt] : privilege.step,  // 比权限所定义的step大的，此审批员一定是审批通过了的，不管以后是否被拒绝
            },
          });
        }
        if (sStatus === '我已拒绝' ) {  // 在自己这一步拒绝的
          where = Object.assign(where, {
            step: privilege.step,
            isRejected: true,
          });
        }

        where = Object.assign(where, {  // todo: 这里把前面的sType覆盖掉了，要下边根据sType手动过滤
          type: privilege.type,
        });

        // console.log(where);
        let result = await RequestNote.findAll({
          order: [
            ['id', 'DESC']
          ],
          attributes: [
            'id',
            'oid',
            'title',
            'type',
            'isRejected',
            'userStatus',
            'applicantName',
            'step',
            'createdTime',
          ],
          where,
          include: [{   // 获取到这个申请单的申请人，这里Users只能有一个元素，那就是申请人
            model: User.scope('all'),
            attributes: ['username', 'id', 'phone', 'email'],
            through: {
              where: {
                step: 0,
              },
            },
          }],
        });
        result = result.filter((r) => {
          if (sType) {   // 如果有查找
            return sType === r.type;
          }
          return true;
        });
        result = result.map((r) => {  // 这里是展示给用户的，因为用户搜索全部的时候也要展示
          let approvalStatus = '待审批';
          if(r.step > privilege.step) { // 比权限所定义的step大的的就是已同意过的
            approvalStatus = '我已同意';
          }
          if(r.isRejected) {   // 不管在哪一步被拒绝，只要审批员能够看到，说明就是他这一类人拒绝的！
            approvalStatus = '被拒绝';
          }
          return Object.assign(r.dataValues, {
            approvalStatus,
          });
        });
        requestNoteList = requestNoteList.concat(result);
      }

      // 上面根据权限反复查询可能有重复结果，所以要去重
      requestNoteList.sort((a, b) => {  // DESC
        return a.id > b.id ? -1 : 1;
      });
      requestNoteList = requestNoteList.filter((e, i) => {
        if(requestNoteList[i + 1]) {
          return e.id !== requestNoteList[i + 1].id;
        }
        return true;
      });

      totalCount = requestNoteList.length;  // 分页前获取总个数
      if( limit !== -1 ) {
        requestNoteList = requestNoteList.slice((page - 1) * limit, page * limit);
      }

      // console.log(requestNoteList[0].Users[0].UserRequestNote);
      requestNoteList = requestNoteList.map((note) => {   // 得到类别名称
        let typeName = '';
        noteTypes.forEach((config) => {
          if( config.enName === note.type ) {
            typeName = config.name;
          }
        });
        return Object.assign(note, {  // 前面dataValues已经用过了
          applicant: note.applicantName,
          createdAt: note.createdTime,
          type: typeName,
          status: note.approvalStatus,
        });
      });

      ctx.body = {
        code: 0,
        msg: {
          total: totalCount,
          requestNoteList,
        }
      };
      return;
    }

    return;
  }

  async getRequestNoteContent(ctx) {
    let { oid } = ctx.request.body;
    const user = ctx.user;
    const approvalPrivileges = user.ApprovalPrivileges || [];  // 得到审批权限

    let requestNote = await RequestNote.findOne({
      where: {
        oid,
      }
    });
    if(!requestNote) {
      ctx.body = {
        code: 20,
        msg: {
          error: '没有此申请单',
        }
      };
      return;
    }

    // 设置好一些属性
    requestNote = requestNote.dataValues;
    requestNote.files = [{
      url: requestNote.fileUrl,
      name: requestNote.filename,
    }];

    let isApprover = false;  // 是否是审批员
    for( let privilege of approvalPrivileges ) {
      if( privilege.type === requestNote.type && privilege.step === requestNote.step ) {
        isApprover = true;
      }
    }


    // 获取到所有的签字信息
    let records = await UserRequestNote.findAll({
      where: {
        RequestNoteId: requestNote.id,
      },
    });
    let userIds = records.map((r) => {
      return r.UserId;
    });
    let users = await User.findAll({   // userIds里面如果有重复的id，只会返回一条
      where: {
        id: userIds
      },
      attributes: ['id', 'username']
    });
    users = userIds.map((id) => {
      let user;
      users.forEach((u) => {
        if(u.id === id) {   // 这里一定能够找到
          user = u;
        }
      });
      return user;
    });

    // todo: 这里用n:m的include查询始终只能获取到一条记录，晕，可能是数据库无法识别两个key都相同的记录吧
    // let users = await User.findAll({  // 这里遍历的所有的人
    //   attributes: ['id', 'username'],
    //   include: {
    //     model: RequestNote,
    //     attributes:['id', 'step', 'title', 'oid'],
    //     through: {
    //       where: {
    //         RequestNoteId: requestNote.id,
    //       }
    //     }
    //   }
    // });
    // console.log(users[0].RequestNotes[0].UserRequestNote);


    // 整合签字信息
    let stepNames = [];  // 签字的所有人的人名
    users.forEach((u, i) => {
      stepNames.push({
        id: records[i].id,  // 签字记录的id
        step: records[i].step,   // 签字记录的step
        signCreatedTime: records[i].signCreatedTime,  // 签字记录的创建时间
        username: u.username,
      });
    });
    stepNames.sort((a, b) => {  // 按照step ASC排序
      return a.step > b.step ? 1 : -1;
    });
    stepNames.forEach((s) => {   // 将stepXName属性放到requestNote里面
      requestNote[`step${s.step}Name`] = s.username;
      requestNote[`step${s.step}Time`] = s.signCreatedTime;  // 签字记录的创建时间
    });

    ctx.body = {
      code: 0,
      msg: {
        requestNoteType: requestNote.type,
        isApprover,
        type: requestNote.type,
        step: requestNote.step,
        isRejected: requestNote.isRejected,
        reason: requestNote.reason,
        requestNote,
        stepNames,
      }
    }

  }

  async addOrUpdateRequestNote(ctx) {
    let { oid, requestNote, action, type } = ctx.request.body;
    const user = ctx.user;
    // console.log(requestNote);
    let note = await RequestNote.findOne({
      where: {
        oid,
      },
      include: [{   // 获取到这个申请单的申请人
        model: User.scope('all'),
        attributes: ['username', 'id', 'phone', 'email'],
        through: {
          where: {
            step: 0,
          },
        },
      }],
    });

    if(note) {  // 如果是更新

      if(note.Users[0].id !== user.id) {  // 如果不是创建的那个人进行的操作
        ctx.body = {
          code: 100,
          msg: "越权操作",
        };
        return;
      }
      // 设置好申请单的各种属性
      requestNote.step = action === 'save' ? 0 : 1;
      requestNote.userStatus = action === 'save' ? '未提交' : '审批中';
      requestNote.filename = requestNote.files ? requestNote.files[0].name : null;
      requestNote.fileUrl = requestNote.files ? requestNote.files[0].url : null;
      requestNote.createdTime = true;  // 提交日期更新一下
      delete requestNote.files;  // 删除files属性
      delete requestNote.oid;   // oid是万万不能更新的!

      await RequestNote.update(requestNote, {
        where: {
          oid,
        }
      });

    } else {  // 如果是创建

      // 设置好申请单的各种属性
      let _index = await RequestNote.count({  // 数一数这个月一共有多少，用来生成oid
        where: {
          createdAt: {
            [Op.gte]: new Date(moment().startOf('month').unix() * 1000),
            [Op.lte]: new Date(moment().endOf('month').unix() * 1000),
          }
        }
      });
      requestNote.oid = _index;
      requestNote.type = type;
      requestNote.step = action === 'save' ? 0 : 1;
      requestNote.userStatus = action === 'save' ? '未提交' : '审批中';
      requestNote.createdTime = true;
      requestNote.filename = requestNote.files ? requestNote.files[0].name : null;
      requestNote.fileUrl = requestNote.files ? requestNote.files[0].url : null;
      delete requestNote.files;  // 删除files属性

      note = await RequestNote.create(requestNote);
      await UserRequestNote.destroy({  // 删除有可能有的旧的创建记录
        where: {
          step: 0,
          RequestNoteId: note.id,
        }
      });
      await UserRequestNote.create({  // 记录下来是这个人创建了这个申请单
        step: 0,
        UserId: user.id,
        RequestNoteId: note.id,
        signCreatedTime: true,
      });

    }

    if( action === 'commit' ) {  // 为所有具有审批权限的审批员 存储消息、异步推送邮件
      let approvers = await User.findAll({
        attributes: ['id', 'email', 'phone', 'username'],
        include: [{
          model: ApprovalPrivileges,
          as: 'ApprovalPrivileges',
          where: {
            step: 1,
            type: requestNote.type,
          }
        }]
      });
      approvers.forEach((app) => {
        if(app.email) {
          sendMail(app.email, '审批提醒', `T3行李运维平台消息：您有一个新的申请单《${requestNote.title}》待审批，请及时查看`);
        }

        Message.create({
          title: '审批提醒',
          content: `您有一个新的申请单《${requestNote.title}》待审批，请及时查看`,
          UserId: app.id,
        });
      });
    }

    ctx.body = {
      code: 0,
      msg: {},
    };
  }

  async approvalRequestNote(ctx) {
    let { oid, action, reason } = ctx.request.body;
    const user = ctx.user;
    const approvalPrivileges = user.ApprovalPrivileges;  // 获取审批员权限
    let requestNote = await RequestNote.findOne({
      where: {
        oid
      }
    });
    if(! requestNote) {
      ctx.body = {
        code: 10,
        msg: {
          error: 'oid不合法',
        }
      };
      return;
    }

    let isGranted = false;  // 用户是否有权限审批
    for(let privilege of approvalPrivileges) {
      if (privilege.type === requestNote.type && privilege.step === requestNote.step) {
        isGranted = true;
      }
    }
    if (!isGranted) {  // 如果没有权限
      ctx.body = {
        code: 0,
        msg: {
          error: '越权操作',
        }
      };
      return;
    }

    let type = requestNote.type; // 类型
    let currentStep = requestNote.step; // 这一步的值
    let currentStepAppName = ''; // 这一步的审批员的名称
    let nextStep = currentStep;  // 下一步的值，如果下面没有找到相应的nextStep，就不变
    noteTypes.forEach((note) => {
      if(note.enName === type) {   // 如果类型相同
        note.steps.forEach((s, idx) => {
          if(s.value === currentStep) {
            currentStepAppName = s.name || '';
            // 下面这句话就含有对变更申请的特殊处理
            // 因为变更申请的steps会直接跳到1001，所以变更申请单没有step为1000即进行中的状态
            nextStep = note.steps[idx + 1] ? note.steps[idx + 1].value : 1000;  // 如果没有了就是进行中

            // 对变更申请单的特殊处理
            if( requestNote.type === 'RequestChange' && currentStep === 4) {   // 由于配置文件同时被超级管理员读取，而填写现场情况描述又不是审批权限，所以这里要特殊处理一下
              nextStep = 1001;
            }
            if(requestNote.type === 'RequestChange' && currentStep === 1005) {  // 用户需要填写变更回顾内容，上面会直接跳到1007
              nextStep = 1006;
            }
            if (requestNote.type === 'RequestChange' && currentStep === 1009) {  // 如果是变更申请的最后一步，是需要用户关闭的，所加一个step特殊处理
              nextStep = 1010;
            }

          }
        });
      }
    });

    if (action === 'refuse') {  // 如果是拒绝

      let _step = requestNote.step;

      // 对变更申请的特殊处理，如果1002、1003、1004拒绝，则重新回到1001这一步
      if(requestNote.type === 'RequestChange' && (requestNote.step === 1002 || requestNote.step === 1003 || requestNote.step === 1004)){
        _step = 1001;
      }

      // 对变更申请的特殊处理，如果1007、1008、1009拒绝，则重新回到1006这一步
      if(requestNote.type === 'RequestChange' && ( requestNote.step === 1007 || requestNote.step === 1008 || requestNote.step === 1009 )) {
        _step = 1006;
      }

      await RequestNote.update({  // 置为未通过
        isRejected: true,
        userStatus: '未通过',
        reason,
        step: _step,
      }, {
        where: {
          oid,
        }
      });

    } else {  // 如果是同意

      let userStatus = nextStep === 1000 ? '进行中' : '审批中';
      if( nextStep === 1001 || nextStep === 1006 || nextStep === 1010) {  // 如果是填写变更实施现场情况描述或填写变更回顾内容或变更最后一步
        userStatus = '进行中';
      }

      await RequestNote.update({
        step: nextStep,
        userStatus,  // 特殊的变更审批完成后也是"进行中"的状态文字
      }, {
        where: {
          oid,
        }
      });

      await UserRequestNote.destroy({  // 删除旧的签字记录
        where: {
          step: currentStep,
          RequestNoteId: requestNote.id,
        }
      });
      await UserRequestNote.create({   // 创建签字记录
        step: currentStep,
        UserId: user.id,
        RequestNoteId: requestNote.id,
        signCreatedTime: true,  // 签字时间
      });

    }

    // 推送邮件给申请单创建者
    let record = await UserRequestNote.findOne({
      where: {
        RequestNoteId: requestNote.id,
        step: 0,
      }
    });
    if(record) {
      let UserId = record.UserId;
      let noteCreator = await User.findOne({  // 获取到创建此申请单的用户信息
        attributes: ['id', 'username', 'email', 'phone'],
        where: {
          id: UserId,
        }
      });
      if(noteCreator.email) {
        sendMail(
          noteCreator.email,
          `申请单《${requestNote.title}》已${action === 'refuse' ? '被拒绝' : '通过'}`,
          `T3行李运维平台消息：${currentStepAppName}已${action === 'refuse' ? '拒绝' : '通过'}您的申请单《${requestNote.title}》，请及时查看`
        );
      }
      Message.create({
        title: `申请单《${requestNote.title}》已${action === 'refuse' ? '被拒绝' : '通过'}`,
        content: `${currentStepAppName}已${action === 'refuse' ? '拒绝' : '通过'}您的申请单《${requestNote.title}》，请及时查看`,
        UserId: noteCreator.id,
      })
    }

    ctx.body = {
      code: 0,
      msg: {},
    }

  }

  // 申请单被拒绝后，用户重置申请单
  async resetRequestNote(ctx) {
    let { oid } = ctx.request.body;
    const user = ctx.user;
    let requestNote = await RequestNote.findOne({
      where: {
        oid: oid,
      },
      include: [{   // 获取到这个申请单的申请人
        model: User.scope('all'),
        attributes: ['username', 'id', 'phone', 'email'],
        through: {
          where: {
            step: 0,
          },
        },
      }],
    });
    if(!requestNote) {
      ctx.body = {
        code: 10,
        msg: {
          error: '申请单不存在',
        }
      };
    }
    if (requestNote.Users[0].id !== user.id) {
      ctx.body = {
        code: 100,
        msg: {
          error: '越权操作',
        }
      };
      return;
    }

    // 重置申请单的属性
    await RequestNote.update({
      isRejected: false,
      reason: '',
      step: 0,
      userStatus: '未提交',
      createdAt: new Date()  // 刷新创建时间
    }, {
      where: {
        oid,
      }
    });

    // 清空旧的审批签名信息
    await UserRequestNote.destroy({
      where: {
        UserId: user.id,
        RequestNoteId: requestNote.id,
        step: {
          [Op.gt] : 0
        }
      }
    });

    ctx.body = {
      code: 0,
      msg: {},
    }
  }

  async closeRequestNote(ctx) {
    let { oid } = ctx.request.body;
    const user = ctx.user;
    let requestNote = await RequestNote.findOne({
      where: {
        oid: oid,
      },
      include: [{   // 获取到这个申请单的申请人
        model: User.scope('all'),
        attributes: ['username', 'id', 'phone', 'email'],
        through: {
          where: {
            step: 0,
          },
        },
      }],
    });
    if(!requestNote) {
      ctx.body = {
        code: 10,
        msg: {
          error: '申请单不存在',
        }
      };
    }
    if (requestNote.Users[0].id !== user.id) {
      ctx.body = {
        code: 100,
        msg: {
          error: '越权操作',
        }
      };
      return;
    }
    await RequestNote.update({
      step: 2000,
      userStatus: '已关闭',
    }, {
      where: {
        oid,
      }
    });
    ctx.body = {
      code: 0,
      msg: {}
    }
  }

  async requestChangeAddOnSiteDescription(ctx) {
    let { oid, onSiteDescription, onSiteTestDescription, onSiteTestResult, onSiteSupervisor } = ctx.request.body;
    const user = ctx.user;
    let requestNote = await RequestNote.findOne({
      where: {
        oid: oid,
      },
      include: [{   // 获取到这个申请单的申请人
        model: User.scope('all'),
        attributes: ['username', 'id', 'phone', 'email'],
        through: {
          where: {
            step: 0,
          },
        },
      }],
    });
    if(!requestNote) {
      ctx.body = {
        code: 10,
        msg: {
          error: '申请单不存在',
        }
      };
    }
    if (requestNote.Users[0].id !== user.id) {
      ctx.body = {
        code: 100,
        msg: {
          error: '越权操作',
        }
      };
      return;
    }

    let currentStep = 1001;
    let nextStep = 1002;
    if(requestNote.isNeedCooperate === '否') {  // 如果不需要第三方联系人，直接跳过第三方联系人审批
      nextStep = 1003;
    }

    await RequestNote.update({
      step: nextStep,              // 对变更申请的特殊处理
      onSiteDescription,
      onSiteTestDescription,
      onSiteTestResult,
      onSiteSupervisor,
      userStatus: '审批中',  // 变更核实者审批中
      isRejected: false,   // 重新置为未拒绝
      reason: '',
    }, {
      where: {
        oid,
      }
    });

    await UserRequestNote.destroy({  // 删除旧的签字记录
      where: {
        step: currentStep,
        RequestNoteId: requestNote.id,
      }
    });
    await UserRequestNote.create({
      step: currentStep,
      UserId: user.id,
      RequestNoteId: requestNote.id,
      signCreatedTime: true,
    });

    // 推送邮件给下一步的审批员
    let approvers = await User.findAll({
      attributes: ['id', 'email', 'phone', 'username'],
      include: [{
        model: ApprovalPrivileges,
        as: 'ApprovalPrivileges',
        where: {
          step: nextStep,
          type: requestNote.type,
        }
      }]
    });
    approvers.forEach((app) => {
      if(app.email) {
        sendMail(app.email, '审批提醒', `T3行李运维平台消息：您有一个新的申请单《${requestNote.title}》待审批，请及时查看`);
      }

      Message.create({
        title: '审批提醒',
        content: `您有一个新的申请单《${requestNote.title}》待审批，请及时查看`,
        UserId: app.id,
      })
    });

    ctx.body = {
      code: 0,
      msg: {},
    }
  }

  // 变更核实者进行核实，也是一种审批，其实是一种没有拒绝权限的签名
  async requestChangeVerify(ctx) {
    let { oid, verifyContent } = ctx.request.body;
    const user = ctx.user;
    let requestNote = await RequestNote.findOne({
      where: {
        oid: oid,
      },
      include: [{   // 获取到这个申请单的申请人
        model: User.scope('all'),
        attributes: ['username', 'id', 'phone', 'email'],
        through: {
          where: {
            step: 0,
          },
        },
      }],
    });
    if(!requestNote) {
      ctx.body = {
        code: 10,
        msg: {
          error: '申请单不存在',
        }
      };
    }
    if (requestNote.Users[0].id !== user.id) {
      ctx.body = {
        code: 100,
        msg: {
          error: '越权操作',
        }
      };
      return;
    }

    let currentStep = 1005;
    let nextStep = 1006;

    await RequestNote.update({
      step: nextStep,              // 对变更申请的特殊处理
      verifyContent,
      userStatus: '进行中',
    }, {
      where: {
        oid,
      }
    });

    await UserRequestNote.destroy({  // 删除旧的签字记录
      where: {
        step: currentStep,
        RequestNoteId: requestNote.id,
      }
    });
    await UserRequestNote.create({
      step: currentStep,
      UserId: user.id,
      RequestNoteId: requestNote.id,
      signCreatedTime: true,
    });

    ctx.body = {
      code: 0,
      msg: {},
    }
  }

  async requestChangeAddReview(ctx) {
    let { oid, reviewCode, reviewExplain, reviewCloseCode } = ctx.request.body;
    const user = ctx.user;
    let requestNote = await RequestNote.findOne({
      where: {
        oid: oid,
      },
      include: [{   // 获取到这个申请单的申请人
        model: User.scope('all'),
        attributes: ['username', 'id', 'phone', 'email'],
        through: {
          where: {
            step: 0,
          },
        },
      }],
    });
    if(!requestNote) {
      ctx.body = {
        code: 10,
        msg: {
          error: '申请单不存在',
        }
      };
    }
    if (requestNote.Users[0].id !== user.id) {
      ctx.body = {
        code: 100,
        msg: {
          error: '越权操作',
        }
      };
      return;
    }

    const currentStep = 1006;
    const nextStep = 1007;

    await RequestNote.update({
      isRejected: false,    // 这里变更申请重新填写了以后要将isRejected置为false，表示我重新提交了
      step: nextStep,
      reviewCode,
      reviewExplain,
      reviewCloseCode,
      userStatus: '审批中',
    }, {
      where: {
        oid,
      }
    });

    await UserRequestNote.destroy({  // 删除旧的签字记录
      where: {
        step: currentStep,
        RequestNoteId: requestNote.id,
      }
    });
    await UserRequestNote.create({
      step: currentStep,
      UserId: user.id,
      RequestNoteId: requestNote.id,
      signCreatedTime: true,
    });

    // 推送邮件给下一步的审批员
    let approvers = await User.findAll({
      attributes: ['id', 'email', 'phone', 'username'],
      include: [{
        model: ApprovalPrivileges,
        as: 'ApprovalPrivileges',
        where: {
          step: nextStep,
          type: requestNote.type,
        }
      }]
    });
    approvers.forEach((app) => {
      if(app.email) {
        sendMail(app.email, '审批提醒', `T3行李运维平台消息：您有一个新的申请单《${requestNote.title}》待审批，请及时查看`);
      }

      Message.create({
        title: '审批提醒',
        content: `您有一个新的申请单《${requestNote.title}》待审批，请及时查看`,
        UserId: app.id,
      });
    });

    ctx.body = {
      code: 0,
      msg: {},
    }
  }
}

module.exports = new RequestAndApprovalController();
